<template>
  <el-header class="header">
    <!-- 1. 左侧：折叠按钮 + 标题 -->
    <div class="left">
      <i
        :class="['fold', isCollapse ? 'el-icon-s-unfold' : 'el-icon-s-fold']"
        @click="toggleSidebar"
      ></i>
      <span class="title"><Breadcrumb /></span>
    </div>

    <!-- 2. 中间搜索 -->

    <!-- <el-input
      v-model="keyword"
      class="search"
      placeholder="站内搜索"
      prefix-icon="el-icon-search"
      clearable
    /> -->

    <!-- 3. 右侧功能区 -->
    <div class="right">
      <!-- 主题切换 -->
      <el-tooltip content="切换主题">
        <i
          :class="['theme', theme === 'light' ? 'el-icon-sunny' : 'el-icon-moon']"
          @click="toggleTheme"
        ></i>
      </el-tooltip>

      <!-- 消息中心 -->
      <!-- <el-badge :value="3" class="badge">
        <i class="el-icon-bell"></i>
      </el-badge> -->

      <!-- 头像下拉 -->
      <el-dropdown trigger="hover" placement="bottom-end">
        <div class="avatar-box">
          <el-avatar size="small" :src="currentUser.avatar || ''">
            <UserFilled v-if="!currentUser.avatar" />
            <!-- 无头像时显示默认图标 -->
          </el-avatar>
          <!-- 动态用户名：显示登录用户的 username，未加载时显示占位符 -->
          <span class="name">{{ currentUser.username || '加载中...' }}</span>
          <i class="el-icon-caret-bottom arrow"></i>
        </div>

        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="person">
              <i class="el-icon-user"></i> 个人中心
            </el-dropdown-item>
            <el-dropdown-item> <i class="el-icon-lock"></i> 锁定屏幕 </el-dropdown-item>
            <el-dropdown-item divided @click="logout">
              <i class="el-icon-switch-button"></i> 退出登录
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </el-header>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'
import { authApi } from '@/api'
import { ElMessage } from 'element-plus'
import Breadcrumb from '@/components/Breadcrumb.vue'

import { Check, Delete, Edit, Message, Search, Star } from '@element-plus/icons-vue'
const userStore = useUserStore()
const router = useRouter()
const currentUser = computed(() => userStore.userInfo || {})

/* ---------- 搜索、主题、折叠 ---------- */
const keyword = ref('')
const theme = ref('light')
const isCollapse = ref(false)

const toggleTheme = () => (theme.value = theme.value === 'light' ? 'dark' : 'light')
const toggleSidebar = () => (isCollapse.value = !isCollapse.value)

/* ---------- 退出登录 ---------- */

const logout = async () => {
  try {
    console.log('🚪 开始退出登录流程...')

    // 第一步：立即设置退出登录标志，防止路由守卫干扰
    localStorage.setItem('logging-out', 'true')
    console.log('🏷️  已设置退出登录标志')

    // 第二步：调用后端退出登录接口（如果需要）
    try {
      await authApi.logout()
      console.log('✅ 后端退出登录成功')
    } catch (apiError) {
      console.warn('⚠️  后端退出登录接口调用失败，继续本地退出:', apiError)
    }

    // 第三步：清除用户状态
    await userStore.logout()
    console.log('🧹 用户状态清除完成')

    // 第四步：显示成功消息
    ElMessage.success('退出登录成功')

    // 第五步：等待一小段时间确保状态清除完成，然后跳转
    await new Promise((resolve) => setTimeout(resolve, 100))

    console.log('🚀 准备跳转到登录页...')
    await router.push('/login')
    console.log('✅ 退出登录流程完成')
  } catch (error) {
    console.error('❌ 退出登录过程中发生错误:', error)
    ElMessage.warning('退出登录过程中发生错误，但已清除本地登录状态')

    // 即使出错也要确保彻底清除状态并跳转
    try {
      localStorage.setItem('logging-out', 'true')
      await userStore.logout()
    } catch (storeError) {
      console.error('清除用户状态失败:', storeError)
      // 手动清除关键信息
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.setItem('logging-out', 'true')
    }

    // 强制跳转到登录页
    console.log('🚀 强制跳转到登录页...')
    router.push('/login')
  }
}
const person = () => {
  router.push('/profile')
}
</script>

<style scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
  padding: 0 24px;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}
.left {
  display: flex;
  align-items: center;
  gap: 16px;
}
.fold {
  font-size: 18px;
  cursor: pointer;
  transition: transform 0.2s;
}
.fold:hover {
  transform: scale(1.1);
}
.title {
  font-size: 16px;
  font-weight: 600;
}
.search {
  width: 320px;
}
.right {
  display: flex;
  align-items: center;
  gap: 16px;
}
.theme,
.el-icon-bell {
  font-size: 18px;
  cursor: pointer;
  transition: color 0.2s;
}
.theme:hover,
.el-icon-bell:hover {
  color: var(--el-color-primary);
}
.avatar-box {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background 0.2s;
}
.avatar-box:hover {
  background: #f5f5f5;
}
.name {
  margin: 0 6px;
  font-size: 14px;
}
.arrow {
  font-size: 12px;
  color: #666;
}
</style>
